<template>
  <div>
    <div class="container">
      <h2>学员课时卡消耗统计</h2>
      <el-divider />

      <!-- 表格展示 -->
      <el-table :data="pagedData" stripe>
        <el-table-column prop="studentId" label="学员ID" />
        <el-table-column prop="cardName" label="课时卡名称" />
        <el-table-column prop="totalClasses" label="总课时" />
        <el-table-column prop="remainingClasses" label="剩余课时" />
        <el-table-column label="已用课时" :formatter="usedClassesFormatter" />
        <el-table-column prop="price" label="价格（元）" />
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" background layout="prev, pager, next" :page-size="pageSize" :total="data.length"
        @current-change="handlePageChange" />

      <!-- 图表展示 -->
      <div class="charts">
        <div ref="pieChartDom" class="chart-box" />
        <div ref="barChartDom" class="chart-box" />
        <div ref="lineChartDom" class="chart-box" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const data = ref([])
const pagedData = ref([])
const pageSize = 7
const currentPage = ref(1)

const handlePageChange = (page) => {
  currentPage.value = page
  const start = (page - 1) * pageSize
  const end = start + pageSize
  pagedData.value = data.value.slice(start, end)
}

const usedClassesFormatter = (row) => row.totalClasses - row.remainingClasses

const pieChartDom = ref()
const barChartDom = ref()
const lineChartDom = ref()

let pieChart = null
let barChart = null
let lineChart = null

const renderCharts = () => {
  if (!pieChart && pieChartDom.value) pieChart = echarts.init(pieChartDom.value)
  if (!barChart && barChartDom.value) barChart = echarts.init(barChartDom.value)
  if (!lineChart && lineChartDom.value) lineChart = echarts.init(lineChartDom.value)

  // 饼图
  const totalUsed = data.value.reduce((sum, item) => sum + (item.totalClasses - item.remainingClasses), 0)
  const totalRemaining = data.value.reduce((sum, item) => sum + item.remainingClasses, 0)

  const pieOption = {
    title: {
      text: '课时使用总体占比',
      subtext: `总课时数：${totalUsed + totalRemaining}，已用 ${totalUsed}，剩余 ${totalRemaining}`,
      left: 'center'
    },
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'horizontal',
      left: 'center',
      top: 'bottom',
      textStyle: {
        fontSize: 13,
        lineHeight: 18
      }
    },
    color: ['#FF6B6B', '#4ECDC4'],
    series: [{
      name: '课时使用情况',
      type: 'pie',
      radius: ['45%', '65%'],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: 'inside',
        formatter: '{d}%',
        fontSize: 15
      },
      labelLine: {
        show: false
      },
      data: [
        { value: totalUsed, name: '已用课时' },
        { value: totalRemaining, name: '剩余课时' }
      ]
    }]
  }

  // 柱状图
  const grouped = {}
  data.value.forEach(item => {
    if (!grouped[item.cardName]) grouped[item.cardName] = []
    grouped[item.cardName].push(item.remainingClasses)
  })

  const cardNames = Object.keys(grouped)
  const avgRemaining = cardNames.map(name => {
    const list = grouped[name]
    return (list.reduce((a, b) => a + b, 0) / list.length).toFixed(1)
  })

  const barOption = {
    title: { text: '各类课时卡平均剩余课时' },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const index = params[0].dataIndex
        const name = cardNames[index]
        return `${name}<br/>平均剩余课时：${params[0].value}`
      }
    },
    xAxis: {
      type: 'category',
      data: cardNames.map((_, i) => `卡${i + 1}`),
      axisLabel: { show: false }
    },
    yAxis: {
      type: 'value',
      name: '平均剩余课时'
    },
    series: [{
      data: avgRemaining,
      type: 'bar',
      itemStyle: { color: '#5B8FF9' }
    }]
  }

  // 散点图
  const scatterData = data.value.map(item => ({
    value: [item.price, item.remainingClasses],
    name: item.cardName
  }))

  const scatterOption = {
    title: { text: '价格 vs 剩余课时（散点图）' },
    tooltip: {
      formatter: function (param) {
        return `${param.data.name}<br/>价格：¥${param.data.value[0]}<br/>剩余课时：${param.data.value[1]}`
      }
    },
    xAxis: {
      name: '价格（元）',
      type: 'value'
    },
    yAxis: {
      name: '剩余课时',
      type: 'value'
    },
    series: [{
      symbolSize: 14,
      data: scatterData,
      type: 'scatter',
      itemStyle: { color: '#73C0DE' }
    }]
  }

  // 渲染所有图表
  pieChart.setOption(pieOption)
  barChart.setOption(barOption)
  lineChart.setOption(scatterOption)
}

onMounted(async () => {
  const res = await axios.get('http://localhost:8080/api/class-cards')
  data.value = res.data
  handlePageChange(1)
  await nextTick()
  renderCharts()
})

window.addEventListener('resize', () => {
  pieChart?.resize()
  barChart?.resize()
  lineChart?.resize()
})
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
}

.pagination {
  margin: 20px 0;
  text-align: center;
}

.charts {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  gap: 20px;
  margin-top: 60px;
}

.chart-box {
  width: 32%;
  /* 三个图表一行，留点间距 */
  min-width: 320px;
  height: 400px;
  flex: none;
}
</style>
